package com.gridmobi.xrtb.handler;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

@Service
public class IDFilter {
    private static final Logger errorlogger = LoggerFactory.getLogger("errorLog");

    // id 过滤
    ConcurrentHashMap<String, Boolean> concurrentSet = new ConcurrentHashMap<>();
    LongAdder count = new LongAdder();

    public Boolean filter(String idfa, String idfv, String oaid){
        String id = idfa;
        if (StringUtils.isEmpty(id)) {
            id = idfv;
        }

        if (StringUtils.isEmpty(id)) {
            id = oaid;
        }
        String last8 = id.substring(id.length() - 8);

        if (concurrentSet.containsKey(last8)) {
            count.add(1);
            return true;
        }

        concurrentSet.put(last8, true);

        return false;
    }

    @Scheduled(cron = "0 0 0 * * ?", zone = "GMT")
    public void clearData() {
        concurrentSet.clear();
        concurrentSet = new ConcurrentHashMap<>();
        errorlogger.error("repeat_count = {}",count.intValue());
        count = new LongAdder();
    }

}
